package com.powernobug.service.impl;

import com.github.pagehelper.PageHelper;
import com.powernobug.bean.model.MarketRegion;
import com.powernobug.bean.vo.PageVo;
import com.powernobug.mapper.MarketRegionMapper;
import com.powernobug.service.AdminRegionService;
import com.powernobug.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: 肖云戈
 * @CreateTime: 2024-08-21
 * @Description:
 */
public class AdminRegionServiceImpl implements AdminRegionService {
    private static SqlSession tempSession;


    @Override
    public PageVo getAllRegionList() {
        tempSession = MyBatisUtil.getSqlSession();
        MarketRegionMapper marketRegionMapper = tempSession.getMapper(MarketRegionMapper.class);
        PageHelper.startPage(1, 20);
        List<MarketRegion> provinces = marketRegionMapper.selectByType((byte) 1);
        List<MarketRegion> cities = marketRegionMapper.selectByType((byte) 2);
        List<MarketRegion> areas = marketRegionMapper.selectByType((byte) 3);
        MyBatisUtil.releaseSqlSession(tempSession);

        packageRegion(cities, areas);
        packageRegion(provinces, cities);

        return PageVo.pag(provinces);
    }

    private static void packageRegion(List<MarketRegion> father, List<MarketRegion> children) {
        Map<Integer, List<MarketRegion>> childrenMap = children.stream()
                .collect(Collectors.groupingBy(MarketRegion::getPid));
        father.forEach(x->x.setChildren(childrenMap.get(x.getId())));
    }
}
